﻿using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Mvc;
using StudentManage.Model;
using StudentManage.ViewModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace StudentManage.Controllers
{
    [Route("[controller]/[action]")]
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;


        /// <summary>
        /// 使用构造函数的方式注入 IStudentRepository
        /// </summary>
        /// <param name="studentRepository"></param>
        public HomeController(IStudentRepository studentRepository)
        {
            _studentRepository = studentRepository;
        }

        [Route("")]
        [Route("~/")]
        [Route("Index")]
        [Route("/Home")]
        public ViewResult Index()
        {
            IEnumerable<Student> student = _studentRepository.GetAllStudents();
            return View(student);
        }

        [Route("{id?}")]
        public IActionResult Details(int? id)
        {
            //返回用户
            HomeDetailsViewModel homeDetailsViewModel = new HomeDetailsViewModel()
            {
                student = _studentRepository.GetStudent(id ?? 1),
                PageTitle = "学生详细信息"
            };
            return View(homeDetailsViewModel);
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photo != null)
                {
                    

                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photo.FileName;
                    

                }
                Student newStudent = new Student
                {
                    Name = model.Name,
                    Email = model.Email,
                    ClassName = model.ClassName,
                    PhotoPath = uniqueFileName
                };
                _studentRepository.Add(newStudent);

                return RedirectToAction("Details", new { id = newStudent.Id });
            }
            return View();
        }
    }
}
